package com.foreverwin.jzymes.archive;

import com.foreverwin.jzymes.archive.domain.DataArchive;
import com.foreverwin.jzymes.archive.service.IDataArchiveAdviceService;
import com.foreverwin.jzymes.framework.util.SpringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;

public class ArchiveDataTask implements Runnable {

    private IDataArchiveAdviceService dataArchiveAdviceService;
    private DataArchive dataArchive;
    private List<DataArchive> referDataArchiveList;
    private List<String> syncFields;
    private List<String> primaryKeys;
    private Map<String,Object> data;
    private boolean delete;

    public ArchiveDataTask( DataArchive dataArchive, List<DataArchive> referDataArchiveList, List<String> syncFields, List<String> primaryKeys, Map<String,Object> data, boolean delete ) {
        this.dataArchive = dataArchive;
        this.referDataArchiveList = referDataArchiveList;
        this.syncFields = syncFields;
        this.primaryKeys = primaryKeys;
        this.data = data;
        this.delete = delete;
        this.dataArchiveAdviceService = SpringUtils.getBean(IDataArchiveAdviceService.class);
    }

    @Override
    public void run() {
        List<Future> futureList = new ArrayList<>();
        for( DataArchive dataArchive : referDataArchiveList ){
            if( delete ){
                dataArchive.setDeleteAfterSync( this.dataArchive.getDeleteAfterSync() );
            }
            ArchiveTask task = new ArchiveTask( dataArchive, data );
            FutureTask future = new FutureTask( task, null );
            futureList.add( future );
            new Thread( future ).start();
        }

        for( Future future : futureList ){
            try {
                future.get();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }

        if( dataArchiveAdviceService.doUpdateArchive( data, dataArchive.getArchiveTable(), syncFields, primaryKeys ) == 0 ){
            dataArchiveAdviceService.doInsertArchive( data, dataArchive.getArchiveTable(), syncFields );
        }
        if( delete ){
            dataArchiveAdviceService.doDelete( data, dataArchive.getTableName(), primaryKeys );
        }
        dataArchiveAdviceService.updateArchiveCount( dataArchive.getTableName(), 1 );
    }


}
